package com.itheima.controller;

import com.itheima.controller.Response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String path;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String OriginalFilename = file.getOriginalFilename();
        String suffix = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        log.info("文件名:{}",fileName);

        File imgFile = new File(path);
        if (!imgFile.exists()){
            imgFile.mkdirs();
        }
        try {
            file.transferTo(new File(path+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);

    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        File file = new File(path+name);
        FileInputStream fis=null;
        try {
            fis = new FileInputStream(file);
            byte[] bytes = new byte[1024*8];
            int length=0;
            while((length=fis.read(bytes))!=-1){
                response.getOutputStream().write(bytes,0,length);
                response.flushBuffer();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
